package shop.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import shop.DAO.UserDAO;
import shop.bean.UserBean;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {


	public void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, java.io.IOException {

		if(request.getParameter("username") != null || request.getParameter("password") != null){			
			try
			{	    

				UserBean user = new UserBean();
				user.setUserName(request.getParameter("username"));
				user.setPassword(request.getParameter("password"));
	
				user = UserDAO.login(user);
	
				if (user.isValid())
				{	
					HttpSession session = request.getSession();	    
					session.setAttribute("currentUser",user); 
					response.sendRedirect("service"); //logged-in page      		     		
				}
	
				else 
					response.sendRedirect("invalidLogin.jsp"); //error page 
			} 
	
	
			catch (Throwable theException) 	    
			{
				System.out.println(theException); 
			}
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, java.io.IOException {
		
		if(request.getParameter("logoff") != null){
			HttpSession session = request.getSession();	    
			session.setAttribute("currentUser",null);
		}
		
		RequestDispatcher rd = request.getRequestDispatcher("login.jsp"); 
        rd.forward(request,response);
	}
}